package cn.xianshu.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static cn.xianshu.constants.RabbitMQConstans.*;

@Configuration
public class RabbitMQConfig {

    // 定义交换机
   @Bean(QUEUE_NAME_OF_TOPIC)
    public Exchange  exchangerNameTopic(){
       return ExchangeBuilder.topicExchange(QUEUE_NAME_OF_TOPIC).durable(true).build();
   }


    // 定义短信队列Bean
    @Bean(QUEUE_NAME_OF_SMS)
    public Queue queueSMS(){
        return new Queue(QUEUE_NAME_OF_SMS, true);
    }


    // 定义邮箱队列Bean
    @Bean(QUEUE_NAME_OF_EMAIL)
    public Queue queueEmail(){
        return new Queue(QUEUE_NAME_OF_EMAIL, true);
    }


    // 定义站内信队列Bean
    @Bean(QUEUE_NAME_OF_MESSAGE)
    public Queue queueMessage(){
        return new Queue(QUEUE_NAME_OF_MESSAGE, true);
    }


    // 定义短信绑定到交换机
    @Bean
    public Binding smsQueueBinding(@Qualifier(QUEUE_NAME_OF_SMS) Queue smsQueue, Exchange exchangerNameTopic){
       // 将smsQueue 绑定到exchangerNameTopic交换机   noarg: 不要其他参数
       return BindingBuilder.bind(smsQueue).to(exchangerNameTopic).with("#.sms").noargs();
    }
    // 定义短信绑定到交换机
    @Bean
    public Binding emailQueueBinding(@Qualifier(QUEUE_NAME_OF_EMAIL) Queue emailQueue, Exchange exchangerNameTopic){
        // emailQueue 绑定到exchangerNameTopic交换机   noarg: 不要其他参数
        return BindingBuilder.bind(emailQueue).to(exchangerNameTopic).with("#.email").noargs();
    }
    // 定义短信绑定到交换机
    @Bean
    public Binding messageQueueBinding(@Qualifier(QUEUE_NAME_OF_MESSAGE) Queue messageQueue, Exchange exchangerNameTopic){
        // messageQueue 绑定到exchangerNameTopic交换机   noarg: 不要其他参数
        return BindingBuilder.bind(messageQueue).to(exchangerNameTopic).with("#.message").noargs();
    }


    //定义RabbitTemplate 指定 JSON转换器
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //1.把要发送的消息内容 ，交换机，rontkey等都保存下来到Mysql
        //2.后续可以用来重写发送消息，甚至可以使用一个定时任务不停的重试，可以甚至一个最大重试次数
        //设置消息回调
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }
}



